<?php

namespace app\common\library\job;

use Exception;
use think\Log;
use think\queue\Job;
use think\Db;

class UpgradeMarketingJob
{

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        Log::write(var_export($data, true), "UpgradeMarketingJob", true);

        $isJobDone = $this->doJob($data);
        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            if ($job->attempts() > 3) {

                $job->delete();

                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 根据消息中的数据进行实际的业务处理...
     */
    private function doJob($data)
    {
        
        try {
            
            $user_id = $data["user_id"] ?? 0;
            echo 'user_id='.$user_id.PHP_EOL;
            $user = db("user")->where("id", $user_id)->find();
            if (!$user) {
                Log::write("用户:" . $user["id"] . " 不存在。", "doJob_tips", true);
                return true;
            }

            //已经是市场最高级别，不作处理
            if ($user["marketing_level"] == 3) {
                Log::write("用户:" . $user["id"] . " 已经是市场最高级别，不作处理。", "doJob_tips", true);
                return true;
            }

            //后台设定不自动升级
            if (!$user["is_auto_upgrade_marketing"]) {
                Log::write("用户:" . $user["id"] . " 后台设定不自动升级。", "doJob_tips", true);
                return true;
            }
            $config_direct_thrust = config("site.direct_thrust");

            $config_team_total = config("site.team_total");
            $config_level_min_total = config("site.level_min_total");
            
            $config_level2_up_condition = config("site.level2_up_condition");
            $config_level3_up_condition = config("site.level3_up_condition");
            if(empty($config_direct_thrust)){
                echo "config_direct_thrust={$config_direct_thrust}".PHP_EOL;
                 return true;
            }
            if(empty($config_team_total)){
                echo "config_team_total={$config_team_total}".PHP_EOL;
                 return true;
            }
            if(empty($config_level_min_total)){
                echo "config_level_min_total={$config_level_min_total}".PHP_EOL;
                 return true;
            }
            if(empty($config_level2_up_condition)){
                echo "config_level2_up_condition={$config_level2_up_condition}".PHP_EOL;
                 return true;
            }
            if(empty($config_level3_up_condition)){
                echo "config_level2_up_condition={$config_level2_up_condition}".PHP_EOL;
                 return true;
            }
            
            echo PHP_EOL."升级条件配置-一星董事升级-直推：{$config_direct_thrust} 一星董事团队总人数达到：{$config_team_total} 一星董事升级-排除最大数达：{$config_level_min_total} 二星董事升级条件：{$config_level2_up_condition} 三星董事升级条件：{$config_level3_up_condition}".PHP_EOL;
//             return true;
            $note = "队列升级";
            $old_marketing_level = $user["marketing_level"];
            $new_marketing_level = $user["marketing_level"]; //将要达标的董事 等级； 初始化为 $user["marketing_level"] 目前是跳过已经升级过的等级 
//            var_dump($new_marketing_level,$new_marketing_level == 0);
            //不是董事 升级 一星董事
            if($new_marketing_level == 0){
                $children_ids = db("user")->where("parent_user_id", $user_id)->where("expert_level", ">", 0)->column('id'); 
                $children_ids = empty($children_ids)?[]:$children_ids;
                $children_count = count($children_ids); ////直推达人总人数
                $team_count = Db::name("user_team_count")->whereIn('user_id',$children_ids)->sum("expert_count");  //直推团体总人数
                $team_max_count = Db::name("user_team_count")->whereIn('user_id',$children_ids)->max('expert_count'); //直推团队最大人数团体
                $team_min_team_count = $team_count - $team_max_count; //小区总数
                //一星董事升级要求：
                //1、自己是二星达人或三星达人；
                //2、完成6个直推（一二三星达人都行）
                //3、6个直推市场的团队总人数达到200个，除去一个最大直推市场，其他直推市场加起来大于100个；
                echo PHP_EOL."团队网体人数:{$team_count} 直推达人总人数:{$children_count} 直推团队最大人数团体:{$team_max_count} 去最大区总数：{$team_min_team_count}".PHP_EOL;
                if ($children_count >= $config_direct_thrust && $team_count >= $config_team_total && $team_min_team_count >= $config_level_min_total) {
                    $new_marketing_level = 1;
                }
            }
            // 一星董事升级 二星董事
            if ($new_marketing_level == 1) {
                $children1_count = db("user")->where("parent_user_id", $user_id)->where(["marketing_level"=>[">=",1]])->count();
                echo "{升级二星董事-直推一星董事数：{$children1_count}}".PHP_EOL;
                if ($children1_count >= $config_level2_up_condition) {
                    $new_marketing_level = 2;
                }
                unset($children1_count);
            }
            // 二星董事升级 三星董事
            if ($new_marketing_level == 2) {
                //检测三星董事升级条件：直推三个二星董事 并且 自己是二星董事 
                $children_count2 = db("user")->where("parent_user_id", $user_id)->where(["marketing_level"=>[">=",2]])->count();
                if ($children_count2 >= $config_level3_up_condition) {
                    $new_marketing_level = 3;
                } 
                unset($children_count2);
            }
            //旧级别比新级别要高，不作处理
            if ($old_marketing_level >= $new_marketing_level) {
                Log::write("用户:" . $user["id"] . " 旧级别:" . $old_marketing_level . " 新级别:" . $new_marketing_level . ",旧级别比新级别相同或更高,不作处理。", "doJob_tips", true);
                return true;
            }

            //当前用户可以升级
            if ($new_marketing_level > 0) {
                //更新级别
                db("user")->where("id", $user_id)->update([
                    "marketing_level" => $new_marketing_level
                ]);
                //添加级别变更历史
                db("expert_upgrade_history")->insert([
                    "is_system" => 1,
                    "admin_id" => 0,
                    "user_id" => $user_id,
                    "before_level" => $old_marketing_level,
                    "after_level" => $new_marketing_level,
                    "note" => $note,
                    "addtime" => time(),
                ]);
                Log::write("用户:" . $user["id"] . "新级别:" . $new_marketing_level . ",升级完成", "doJob_tips", true);
            }
        } catch (Exception $e) {
            Log::write($e->getMessage(), "doJob_error", true);
        }

        return true;
    }
    /**
     * 根据消息中的数据进行实际的业务处理...
     */
    private function doJob_Bak_Chao($data)
    {
        try {
            $user_id = $data["user_id"] ?? 0;
            $user = db("user")->where("id", $user_id)->find();
            if (!$user) {
                Log::write("用户:" . $user["id"] . " 不存在。", "doJob_tips", true);
                return true;
            }

            //已经是市场最高级别，不作处理
            if ($user["marketing_level"] == 3) {
                Log::write("用户:" . $user["id"] . " 已经是市场最高级别，不作处理。", "doJob_tips", true);
                return true;
            }

            //后台设定不自动升级
            if (!$user["is_auto_upgrade_marketing"]) {
                Log::write("用户:" . $user["id"] . " 后台设定不自动升级。", "doJob_tips", true);
                return true;
            }


            $note = "队列升级";
            $old_marketing_level = $user["marketing_level"];

            //检测合伙人升级条件：直推三个市场经理
            $new_marketing_level = 0;
            $children_count2 = db("user")->where("parent_user_id", $user_id)->where("marketing_level", 2)->count();
            if ($children_count2 >= 3 ) {
                $new_marketing_level = 3;
            } else {

                //检测市场经理升级条件：直推三个市场总监
                $children1_count = db("user")->where("parent_user_id", $user_id)->where("marketing_level", 1)->count();
                if ($children1_count >= 3) {
                    $new_marketing_level = 2;
                } else {

                    //检测市场总监升级条件：
                    //（1）直推6个达人或以上，
                    // (2) 团队网体人数200以上，
                    // (3) 除去最大区外，直推最小区合计超过100人，

                    $team_count = $user["team_count"]; //团队网体人数
                    $children_list = db("user")->where("parent_user_id", $user_id)->where("expert_level", ">", 0)->select();
                    $child_max_team_count = 0; //最大区
                    $child_total_team_count = 0; //总数：包括大区和小区
                    $child_left_team_count = 0; //小区总数
                    if ($children_list) {
                        foreach ($children_list as  $child) {
                            $child_total_team_count += $child["team_count"];
                            if ($child["team_count"] > $child_max_team_count) {
                                $child_max_team_count = $child["team_count"];
                            }
                        }
                    }
                    $child_left_team_count = $child_total_team_count - $child_max_team_count; //小区总数
                    $children_count = count($children_list); //直推人数

                    //市场总监升级条件：
                    if ($children_count >= 6 && $team_count >= 200 && $child_left_team_count >= 100) {
                        $new_marketing_level = 1;
                    }
                }
            }

            //旧级别比新级别要高，不作处理
            if ($old_marketing_level >= $new_marketing_level) {
                Log::write("用户:" . $user["id"] . " 旧级别:" . $old_marketing_level . " 新级别:" . $new_marketing_level . ",旧级别比新级别相同或更高,不作处理。", "doJob_tips", true);
                return true;
            }

            //当前用户可以升级
            if ($new_marketing_level > 0) {

                //更新级别
                db("user")->where("id", $user_id)->update([
                    "marketing_level" => $new_marketing_level
                ]);

                //添加级别变更历史
                db("expert_upgrade_history")->insert([
                    "is_system" => 1,
                    "admin_id" => 0,
                    "user_id" => $user_id,
                    "before_level" => $old_marketing_level,
                    "after_level" => $new_marketing_level,
                    "note" => $note,
                    "addtime" => time(),
                ]);

                Log::write("用户:" . $user["id"] . "新级别:" . $new_marketing_level . ",升级完成", "doJob_tips", true);
            }
        } catch (Exception $e) {
            Log::write($e->getMessage(), "doJob_error", true);
        }

        return true;
    }
}
